﻿using SCADAEditor.Component;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SCADAEditor
{
    //窗口树的数据结构
    public class WinformTreeDatastruct
    {
        private List<WindowTreeNode> _nodes = new List<WindowTreeNode>();
        private Dictionary<int, List<ComponentBase>> _windowComponents = new Dictionary<int, List<ComponentBase>>();
    
        /// <summary>
        /// 根据窗口ID获取WindowTreeNode
        /// </summary>
        /// <param name="windowId">窗口ID</param>
        /// <returns>对应的WindowTreeNode对象，如果未找到则返回null</returns>
        public WindowTreeNode GetWindowNodeById(int windowId)
        {
            // 在根节点中查找
            var node = Nodes.FirstOrDefault(n => n.Id == windowId);
            if (node != null)
            {
                return node;
            }

            // 递归在子节点中查找
            foreach (var rootNode in Nodes)
            {
                node = FindNodeInChildren(rootNode, windowId);
                if (node != null)
                {
                    return node;
                }
            }

            return null;
        }

        /// <summary>
        /// 递归在子节点中查找窗口节点
        /// </summary>
        private WindowTreeNode FindNodeInChildren(WindowTreeNode parentNode, int windowId)
        {
            foreach (var childNode in parentNode.Children)
            {
                if (childNode.Id == windowId)
                {
                    return childNode;
                }

                var foundNode = FindNodeInChildren(childNode, windowId);
                if (foundNode != null)
                {
                    return foundNode;
                }
            }

            return null;
        }
        
        public List<WindowTreeNode> Nodes 
        {
            get 
            {
                if (_nodes.Count == 0)
                {
                    // 自动创建50个默认节点
                    for (int i = 1; i <= 50; i++)
                    {
                        _nodes.Add(new WindowTreeNode 
                        {
                            Id = i,
                            Name = $"窗口{i}",
                            DisplayName = $"{i}：窗口{i}",
                            Size = new Size(800, 600),
                            BackgroundColor = Color.White
                        });
                    }
                }
                return _nodes;
            }
        }

        // 添加新窗口的方法
        public WindowTreeNode AddWindow(string name, Size size)
        {
            var newNode = new WindowTreeNode
            {
                Id = Nodes.Count + 1,
                Name = name,
                DisplayName = $"{Nodes.Count + 1}：{name}",
                Size = size,
                BackgroundColor = Color.White
            };
            Nodes.Add(newNode);
            return newNode;
        }

        // 添加组件到指定窗口
        public void AddComponentToWindow(int windowId, ComponentBase component)
        {
            if (!_windowComponents.ContainsKey(windowId))
            {
                _windowComponents[windowId] = new List<ComponentBase>();
            }
            _windowComponents[windowId].Add(component);
        }

        // 获取窗口的所有组件
        public List<ComponentBase> GetWindowComponents(int windowId)
        {
            return _windowComponents.ContainsKey(windowId) 
                ? _windowComponents[windowId] 
                : new List<ComponentBase>();
        }

        // 从窗口移除组件
        public bool RemoveComponentFromWindow(int windowId, ComponentBase component)
        {
            if (_windowComponents.ContainsKey(windowId))
            {
                return _windowComponents[windowId].Remove(component);
            }
            return false;
        }

       /// <summary>
        /// 将窗口树结构绑定到TreeView控件
        /// </summary>
        /// <param name="treeView">目标TreeView控件</param>
        public void BindToTreeView(TreeView treeView)
        {
            treeView.Nodes.Clear();
            
            // 添加根节点
            foreach (var node in Nodes)
            {
                var treeNode = new TreeNode(node.DisplayName ?? $"{node.Id}：{node.Name}")
                {
                    Tag = node // 将WindowTreeNode对象存储在Tag中以便后续使用
                };
                
                // 递归添加子节点
                AddChildNodes(treeNode, node.Children);
                
                treeView.Nodes.Add(treeNode);
            }
        }

        /// <summary>
        /// 递归添加子节点
        /// </summary>
        private void AddChildNodes(TreeNode parentTreeNode, List<WindowTreeNode> childNodes)
        {
            foreach (var childNode in childNodes)
            {
                var treeNode = new TreeNode(childNode.DisplayName ?? $"{childNode.Id}：{childNode.Name}")
                {
                    Tag = childNode
                };
                
                // 递归处理子节点的子节点
                AddChildNodes(treeNode, childNode.Children);
                
                parentTreeNode.Nodes.Add(treeNode);
            }
        }

        public void Clear()
        {
            _nodes.Clear();
            _windowComponents.Clear();
        }
    }

     // 窗口树节点类
    public class WindowTreeNode
    {
         [Category("基本信息")]
        public string DisplayName { get; set; }   // 在TreeView中显示的名称
         [Category("基本信息")]
        public string Name { get; set; }          // 窗口名称
         [Category("基本信息")]
        public int Id { get; set; }               // 窗口编号
        [Category("窗口设置")]
        public Size Size { get; set; }            // 窗口大小(宽度，高度)
         [Category("窗口设置")]
        public Color BackgroundColor { get; set; } // 背景颜色
        
        [Category("脚本指令")]
        public string OnOpenCommand { get; set; }    // 窗口打开时执行的代码
         [Category("脚本指令")]
        public string LoopCommand { get; set; }       // 循环执行的代码 
         [Category("脚本指令")]
        public string OnCloseCommand { get; set; }    // 窗口关闭时执行的代码
        [Browsable(false)]  // 隐藏子节点属性，不在PropertyGrid中显示
        public List<WindowTreeNode> Children { get; } = new List<WindowTreeNode>(); // 子节点
    }

}
